# -----------------------------------------------------------------------------
# Copyright (c) 2025, Southeast University (China)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#  - Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  - Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#  - Neither the name of the copyright holders nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Jiajie Xu, Yanfang Zhang, Jiaqi Gao, Leyun Tian
# -----------------------------------------------------------------------------


import gzip

class pin_trans:
    def __init__(self):
        self.name = ''
        self.trans = [None, None] # MaxTrans, Trans
    def __repr__(self):
        trans_repr = f"Max_Trans:{self.trans[0]}, Trans:{self.trans[1]}"
        return f"pin_trans(pin_name={self.name}, trans=[{trans_repr}]"

class port_trans:
    def __init__(self):
        self.name = ''
        self.data = [None, None, None, None, None, None] # SetupRise, SetupFall, HoldRise, HoldFall, MaxTrans, MaxCap
    def __repr__(self):
        data_repr = f"SetupRise_Trans:{self.data[0]}, SetupFall_Trans:{self.data[1]}, HoldRise_Trans:{self.data[2]}, HoldFall_Trans:{self.data[3]}, MaxTrans:{self.data[4]}, MaxCap:{self.data[5]}"
        return f"pin_trans(pin_name={self.name}, trans=[{data_repr}]"

def Read_PtTrans(inrpt):
    """Read pins trans and max_trans from PT report from fast_report_pin_timing, 
    return design max trans, design max caps pin list and port list with drv and trans"""
    pins = {}
    ports = {}
    portFalg = False
    with gzip.open(inrpt, 'rt', encoding='utf-8') as infile:
        for line in infile:
            index = line.split()
            if len(index) > 0:
                if index[0] == "#Design" and index[1] == "design_name" and index[2] == "max_transition" and index[3] == "max_capacitance":
                    next_line = next(infile, '').strip()
                    if next_line:
                        next_index = next_line.split()
                        design_max_trans = float(next_index[1]) if next_index[1] != "*" else None
                        design_max_caps =  float(next_index[2]) if next_index[2] != "*" else None
                # Reading Max transition for pins
                if index[0] == "#MaxTransition" and index[1] == "pins" and index[2] == "max_transition":
                    num_pins = int(index[3])
                    pin_name = []
                    next_line = next(infile, '').strip() # skip line #pins_name ...
                    for i in range(num_pins):
                        next_line = next(infile, '').strip()
                        if next_line:
                            next_index = next_line.split()
                            if len(next_index) > 0:
                                pin_name.append(next_index[0]) # read pin name
                    next_line = next(infile, '').strip() # skip line #max_transition ...
                    max_trans = []
                    for i in range(num_pins):
                        next_line = next(infile, '').strip()
                        if next_line:
                            next_index = next_line.split()
                            if len(next_index) > 0:
                                if next_index[0] == "INFINITY":
                                    max_trans.append(None)
                                else:
                                    max_trans.append(float(next_index[0]))
                    for pinName, maxTrans in zip(pin_name, max_trans):
                        new_pin = pin_trans()
                        new_pin.name = pinName
                        new_pin.trans[0] = maxTrans
                        pins[pinName] = new_pin
                
                # Reading data for ports
                if portFalg:
                    newport = port_trans()
                    newport.name = index[0]
                    for i in range(6):
                        newport.data[i] = float(index[i+1]) if index[i+1] != "*" else None
                    ports[newport.name] = newport
                if index[0] == "#Port" and index[1] == "port_name" and index[2] == "Setup_RiseTrans" and index[3] == "Setup_FallTrans":
                    portFalg = True
                
                # Reading Transition for pins
                if index[0] == "#PinTransition":
                    num_pins = int(index[1])
                    next_line = next(infile, '').strip() # skip line #max_transition ...
                    pin_name = []
                    for i in range(num_pins):
                        next_line = next(infile, '').strip()
                        if next_line:
                            next_index = next_line.split()
                            if len(next_index) > 0:
                                pin_name.append(next_index[0]) # read pin name
                    next_line = next(infile, '').strip() # skip line #actual_rise_transition_max ...
                    actual_rise_trans = []
                    for i in range(num_pins):
                        next_line = next(infile, '').strip()
                        if next_line:
                            next_index = next_line.split()
                            if len(next_index) > 0:
                                actual_rise_trans.append(float(next_index[0]))# read pin actual rise trans
                    for pinName, Trans in zip(pin_name, actual_rise_trans):
                        if pinName in pins.keys():
                            pins[pinName].trans[1] = Trans
                        else:
                            new_pin = pin_trans()
                            new_pin.name = pinName
                            new_pin.trans[1] = Trans
                            pins[pinName] = new_pin
            else:
                portFalg = False
    
    return design_max_trans, design_max_caps, pins, ports

if __name__ == "__main__":
    import sys 
    import os
    sys.path.append("../")
    from Global_var import *
    import work_var
    file = os.path.join(work_var.pt_data_dir, "mc_top/func_slow_data_pin_timing.txt.gz")
    pins, ports = Read_PtTrans(file)
    print(ports)